package org.NooLab.tikaserver;

import java.util.Map;

import org.NooLab.structures.ArgumentsBasicIntf;
import org.NooLab.structures.ArgumentsCliReaderAbstract;
import org.NooLab.structures.ArgumentsPublicIntf;
import org.NooLab.utilities.logging.LogControl;
import org.NooLab.utilities.strings.StringsUtil;



/**
 * 
 * commandline parameters describe the ports to be used:
 *    -in:7201 -out:7102
 *    
 * default values are 7210,7209, in itexx context they are set by CLI arguments
 *    
 * the purpose of this piece is to make tika available in an automated environment;
 * there is a massive problem with the combination processbuilder/tika, preventing
 * tika to find the appropriate classloaders during startup and creating its objects
 * (which uses reflection) as well as its resources.
 * 
 * 
 		-comm: in-7251,out-7210
		-waitfor:0
		-appsecret: 12ahf-23487asdf-3487sdfr-559
		-name:tikasrv
		-loglevel:2
 *
 */
public class TikaServerApp {

	

	// 
	public static void main(String[] args) {

		try {
		
			new TikaServerAppInstance(args) ;

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


@SuppressWarnings("rawtypes")
class Arguments<T> extends ArgumentsCliReaderAbstract implements ArgumentsBasicIntf{

	
	protected ArgumentsPublicIntf arguments ;
	public Map argumentsMap;

	
	
	public Arguments(){
		super();
		setParent( this ) ;
		
	}
	
	
	
	@Override
	protected ArgumentsPublicIntf parse(String[] _args) {
		
		String str="";
		String[] argumentLines = new String[0] ;
		
		try {
			
			if (_args!=null){
				// just port numbers
				if ( _args.length==2){
					/*
					ports = getPorts(ports,str);
					str = _args[1];
					ports = getPorts(ports,str);
					*/
					this._acquirePorts( "comm", "in-"+_args[0]+",out-"+_args[1]);
				}
				
			} // any arguments at all?
			
			// if there is too little information, we check whether there is a CLIA-file
			if ((_args.length==1) || (_args==null) || (_args.length==0)){
				// is it a properties file?
				String argStr="";
				
				
				if ((_args==null) || ((_args.length>0) && (_args[0].trim().length()>0))){
					argStr = "NooLabTikaServer.clia" ;
				}
				if ((_args!=null) && (_args.length>0) &&(_args[0].length()>0)){
					argStr = _args[0];
				}
				argumentLines = loadArgumentsFromFile( argStr ) ;
				arguments = prepareArguments( "", argumentLines ) ;
				
				
			}
			// if we got it through the CLI
			if ( _args.length>=3  ){
				arguments = prepareArguments( "", _args ) ;
			}
 
			_getParticulars();
			
		} catch (Exception e) {
			showArguments( getDescription() );
			System.exit(0);			
		}  

		TikaServerAppInstance.tikaPorts  = (int[])arguments.getMappedTopic("tika");
		
		
		String params = arguments.showActualArguments(0);
		System.out.println("TikaServer has been starting with the following paramaters: \n"+params);

		return this;
	}


	@SuppressWarnings("unchecked")
	private void _getParticulars() {
		// -result:xml
		int rtype=0;
		Map argMap = getArgumentsMap();
		 
		if (handlingTreatment( new String[]{"result","results","return"}) ){
			
			if (argMap.containsKey("result")){
				String rtypestr = (String) argMap.get("result");
				if (rtypestr.toLowerCase().contentEquals("xml")){
					rtype = 1;
				}
				if ((rtypestr.toLowerCase().contentEquals("plain") ||
					(rtypestr.toLowerCase().contentEquals("raw")))){
					rtype = 0;
							
				}
			}
		}
		argMap.put( "result", (T)(Integer)rtype) ;
		
	}



	@Override
	public int[] getServicePorts() {
		return servicePorts;
	}

	@Override
	public String getAppSecret() {
		return appsecret;
	}

	@Override
	public int[] getPorts() {
		return ports;
	}

	@Override
	protected String[] getDescription() {
		String[] description = new String[3];
		return description ;
	}

 
 	
}


@SuppressWarnings("rawtypes")
class TikaServerAppInstance{
	
	
	
	
	ArgumentsPublicIntf arguments ;
	private TikaServerFactory tikaServer;
	static int[] tikaPorts;

 
	public TikaServerAppInstance(String[] args) throws Exception{

		LogControl.Level = 2 ;
		
		String str ;
		int[] ports = new int[]{7210,7209}; // these are default, in itexx context we use commandline !!! 
		
		
		{
			// itexx context
			arguments = (new Arguments()).parse( args ) ;
			
		}
		 
		tikaServer = new TikaServerFactory(arguments);
		
		tikaServer.start(); 

	}

	
	protected void start() throws Exception{
		if (tikaServer!=null){
			tikaServer.start();
		}
	}
	
	
	
	private static int[] getPorts(int[] ports, String str) {
		 
		StringsUtil strgutil = new StringsUtil (); 
		
		int ix=-1;
		
		if (str.toLowerCase().indexOf("-in")>=0){
			ix=0;
			str = str.replace("-in", "");
		}
		if (str.toLowerCase().indexOf("-out")>=0){
			ix=1;
			str = str.replace("-out", "");
		}
		str = str.replace(":", "");

		if (ix>=0){
			if (strgutil.isNumericX(str)){
				int vi = Integer.parseInt(str) ;
				ports[ix] = vi;
			}
		}
		
		return ports;
	}

}

